import logging
import requests
from pathlib import Path
from typing import Any, Dict, List

from .utils import load_json_file

SOURCES_CONFIG_PATH = Path("config/sources.json")

def download_sources() -> List[Dict[str, Any]]:
    """
    从配置文件中列出的URL下载所有书源。
    """
    source_urls = load_json_file(SOURCES_CONFIG_PATH)
    if not source_urls:
        logging.error("书源配置文件为空或无法加载。")
        return []

    all_sources = []
    for source_info in source_urls:
        name = source_info.get("name", "unknown")
        url = source_info.get("url")
        if not url:
            logging.warning(f"跳过名为 '{name}' 的书源，因为它没有URL。")
            continue

        logging.info(f"正在从 {name} ({url}) 下载书源...")
        try:
            response = requests.get(url, timeout=15)
            response.raise_for_status()  # 如果请求失败则引发HTTPError
            
            # 尝试解析JSON
            sources_data = response.json()
            
            # 确保返回的是一个列表
            if isinstance(sources_data, list):
                all_sources.extend(sources_data)
                logging.info(f"成功从 {name} 下载并解析了 {len(sources_data)} 个书源。")
            else:
                logging.warning(f"来自 {name} 的响应不是一个JSON列表，已跳过。")

        except requests.Timeout:
            logging.error(f"从 {name} 下载超时。")
        except requests.RequestException as e:
            logging.error(f"从 {name} 下载时发生网络错误: {e}")
        except ValueError: # requests.models.JSONDecodeError is a subclass of ValueError
            logging.error(f"无法解析来自 {name} 的JSON响应。")

    return all_sources
